<template>
    <Dialog :title="comInfo.name" :show="true" @close="cancel" :width="480" :height="360" :left="uiLeft" :top="uiTop">
        <div class="box">
            <div class="center-table">
                <el-table :data="instanceList" border :cell-style="cellStyle2" ref="tableRef"
                    :header-cell-style="cellStyleSmall">
                    <el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" />
                    <el-table-column prop="id" label="ID" :show-overflow-tooltip="true" width="auto" />
                    <el-table-column prop="name" label="名称" :show-overflow-tooltip="true" width="auto" />
                    <el-table-column label="操作" width="240" align="center">
                        <template #default="scope">
                            <div class="table-operation">
                                <el-button type="primary" size="small" text @click="flyTo(scope.row)" class="btn-img">
                                    <img src="@/assets/common/dingwei.png" /> 定位
                                </el-button>
                                <el-button type="primary" size="small" text @click="property(scope.row)"
                                    class="btn-img">
                                    <img src="@/assets/common/shuxing.png" /> 修改
                                </el-button>
                                <el-button type="primary" size="small" text @click="deleteItem(scope.row.id)"
                                    class="btn-img">
                                    <img src="@/assets/common/shanchu.png" /> 删除
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="bottom">
                <PaginatorCom :currentPage="pages.pageNum" :pageSize="pages.pageSize" :total="total"
                    @update:currentPage="handleCurrentChange" @update:pageSize="handleSizeChange" />
            </div>
        </div>
    </Dialog>

    <TooltipCom v-if="currentDialog == 'delete'" :content="'确认删除吗？'" :title="'删除'" :isVisible="true"
        @close="currentDialog = undefined" @confirm="deleteConfirm" />

    <Edit v-if="currentDialog == 'edit'" :updateInfo="updateInfo" :title="'修改'" :isVisible="true"
        @close="currentDialog = undefined" @confirm="editConfirm" :info="info"></Edit>

</template>
<script lang="ts" setup>
import Dialog from "@/components/Dialog.vue";
import { onMounted, ref, onBeforeUnmount, watch } from "vue";
import { getProjectManager } from "@/scripts/getProjectManager";
import {
    createVueDisposer,
    toVR,
} from "earthsdk-ui";
import { cellStyleSmall, cellStyle2, } from "../../scripts/tableStyle";
import PaginatorCom from "@/components/common/PaginatorCom.vue";
import {
    deleteDantihua,
    reqGetInstanceList,
    reqUpdateMonomer,
    reqGetMonomerProperty
} from "@/api/modelser2Api";
import TooltipCom from "@/components/common/TooltipCom.vue";
import { ElMessage } from "element-plus";
import { getDistancesFromPositions, getMinMaxCorner } from "earthsdk3"
import Edit from "./Edit.vue"
import loading from "@/api/loading";

const props = withDefaults(defineProps<{ comInfo: any }>(), {});
const emits = defineEmits(["cancel"]);
const cancel = () => {
    emits("cancel", props.comInfo.id);
};
const uiLeft = document.body.clientWidth - 10 - 480;
const uiTop = 60;

const d = createVueDisposer(onBeforeUnmount);
const objm = getProjectManager();

const modelserManager = getProjectManager().modelser2Manager;

const monomerEdit = modelserManager.monomerEdit;

// 单体化列表
const instanceList = ref([]);

const total = ref(0);
const currentDialog = ref<any>(undefined)

// 获取单体化列表
const getInstanceList = async () => {
    try {
        const param = {
            ...pages.value,
            tileSerivceName: objm.modelser2Manager.eSMsTileset.tileServiceName,
        };
        const res = await reqGetInstanceList(param);
        // @ts-ignore
        if (res.status != "ok" || !res.data) return (instanceList.value = []);
        instanceList.value = res.data.data;
        total.value = res.data.total

    } catch (error) {
        console.error(error);
    }
}

const delId = ref("")

// 删除
const deleteItem = (id: string) => {
    delId.value = id
    currentDialog.value = 'delete'
}

// 删除确认
const deleteConfirm = async () => {
    try {
        const res = await deleteDantihua({ tileServiceName: objm.modelser2Manager.eSMsTileset.tileServiceName, ids: [delId.value] })
        if (res.status == 'ok') {
            loading.closeLoading()

            ElMessage.success('删除成功')
            currentDialog.value = undefined
            await getInstanceList()
            modelserManager.eSMsTileset.refresh();

        } else {
            loading.closeLoading()

            return
        }
    } catch (err) {
        loading.closeLoading()

        console.log(err)
    }
}

const classDetails = ref({})


// 获取单体化属性列表
const getClassDetails = async () => {
    try {
        const res = await reqGetMonomerProperty({ tileSerivceName: objm.modelser2Manager.eSMsTileset.tileServiceName })
        if (res.status == 'ok' && res.data.data.length > 0) {
            classDetails.value = res.data.data
        } else {
            return classDetails.value = []
        }
    } catch (error) {
        console.log(error)
    }
}

// 设置数据格式
const setFormat = (obj: any) => {
    // 创建一个新的对象，只包含原始对象中不包含在propertiesToRemove中的属性
    let newObj: any = Object.keys(obj)
        .reduce((acc, key) => {
            // @ts-ignore
            acc[key] = obj[key]
            return acc
        }, {})

    const { fields } = newObj
    newObj = { ...fields }

    let arr = Object.keys(newObj).map((key) => {
        // @ts-ignore
        const type = classDetails.value.find((item) => item.name === key)?.type
        // @ts-ignore
        return { key: key, value: newObj[key], type: (type ? type : 'String') }
    })

    // const index = arr.findIndex((item) => item.key === "result")
    // const temp = arr[0];
    // arr[0] = arr[index];
    // arr[index] = temp;
    // 表格数据
    return arr
}

const info = ref<any>([])
const updateInfo = ref<any>([])

// 打开修改面板
const property = (row: any) => {
    row.tileSerivceName = objm.modelser2Manager.eSMsTileset.tileServiceName
    currentDialog.value = "edit"
    info.value = setFormat(row)
    updateInfo.value = row
}

// 修改确认
const editConfirm = async (val: any) => {
    try {
        const res = await reqUpdateMonomer(val)

        if (res.status == 'ok') {
            ElMessage.success('修改成功')
            loading.closeLoading()
            currentDialog.value = undefined
            getInstanceList()
        } else {
            loading.closeLoading()
        }
    } catch (err) {
        loading.closeLoading()
        console.log(err)
    }
}

watch(instanceList, (newVal: any, oldVal: any) => {
    if (!instanceList.value.length) return;
    if (oldVal) {
        const options: any = []

        instanceList.value.forEach((e: any) => {
            options.push({
                condition: [{
                    field: "id",
                    op: "==",
                    value: e.id
                }],
                color: [1, 1, 1, 1],
                show: true
            })
        });
        console.log("oldVal", options);

        objm.modelser2Manager.eSMsTileset.es3DTileset.setFeatureStyle(options);


    }
    if (newVal) {
        const options: any = []
        instanceList.value.forEach((e: any) => {
            options.push({
                condition: [{
                    field: "id",
                    op: "==",
                    value: e.id
                }],
                color: [0, 0, 1, 1],
                show: true
            })
        });
        console.log("newVal", options);
        objm.modelser2Manager.eSMsTileset.es3DTileset.setFeatureStyle(options);

    }

})

const pages = ref({
    pageNum: 1,
    pageSize: 10,
})

/**
 * 监听当前页数变化
 * @param {number} val
 */
const handleCurrentChange = (val: any) => {
    pages.value.pageNum = val
    getInstanceList()
}
/**
 * 监听当前页条数变化
 * @param {number} val
 */
const handleSizeChange = (val: any) => {
    pages.value.pageSize = val
    getInstanceList()
}
// 定位
const flyTo = (row: any) => {
    let points = JSON.parse(row.geom).coordinates[0]
    points = points.map((item: any) => {
        return [item[0], item[1], item[2] ? item[2] : 0]
    })
    const { minPos, maxPos, center } = getMinMaxCorner(points)
    const dis = getDistancesFromPositions([minPos, maxPos], 'NONE')[0] * 2
    const minLng = minPos[0]
    const minLat = minPos[1]
    const maxLng = maxPos[0]
    const maxLat = maxPos[1]
    // 构建边界框 
    const extent = [minLng, minLat, maxLng, maxLat];
    console.log(extent, dis);

    objm.activeViewer.flyTo({ distance: dis, heading: 0, pitch: -60, flyDuration: 1, hDelta: 0, pDelta: 0 }, center)
}

onMounted(() => {
    getInstanceList()
    getClassDetails()
})

onBeforeUnmount(() => {
    if (!instanceList.value.length) return;
    const options: any = []

    instanceList.value.forEach((e: any) => {
        options.push({
            condition: [{
                field: "id",
                op: "==",
                value: e.id
            }],
            color: [1, 1, 1, 1],
            show: true
        })
    });
    console.log("oldVal", options);

    objm.modelser2Manager.eSMsTileset.es3DTileset.setFeatureStyle(options);
})

</script>

<style scoped>
.box {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    padding: 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.center-table {
    height: calc(100% - 35px);
}

.bottom {
    display: flex;
    justify-content: center;
}

.el-table .cell img {
    width: 17px !important;
    height: 18px !important;
    margin-right: 6px;
}

.table-operation button {
    color: #333333 !important;
    margin-left: 1px !important;
}
</style>